<?php

namespace App\Models\Shop;

use App\Helpers\Uploader\UploadImage;
use App\Models\BaseModel;
use Illuminate\Http\Request;

class ShopGoodsPictureModel extends BaseModel
{
    protected $table = 'shop_goods_picture';

    protected $primaryKey = 'id';

    public $dateFormat = 'U';

    public function upload(Request $request)
    {
        $config = config('UEditorUpload.upload');
        $upConfig = array(
            "pathFormat" => $config['imagePathFormat'],
            "callback" => [$this,'fileHasExisted'],
            "maxSize" => $config['imageMaxSize'],
            "allowFiles" => $config['imageAllowFiles'],
            'fieldName' => $request->input('fileInputName',$config['imageFieldName']),
            'imageGroup'=>$request->input('image_group','image')
        );
        $result = with(new UploadImage($upConfig, $request))->upload();
        if($result['status']){
            if($result['state'] == 'SUCCESS'){
                $result['imageGroup'] = $upConfig['imageGroup'];
                $result['id'] = $this->savePicture($result);
            }
        }
        return $result;
    }

    public function savePicture($result)
    {
        $this->type = 'local';
        $this->path = $result['url'];
        $this->group = $result['imageGroup'];
        $this->md5 = $result['md5'];
        $this->sha1 = $result['sha1'];
        $this->status = 1;
        if($this->save()){
           return $this->id;
        }
        return false;
    }

    public function fileHasExisted($file)
    {
        if(empty($file['md5'])){
            throw new \Exception('缺少参数:md5');
        }
        return $this->where([['md5','=',$file['md5']],['sha1','=',$file['sha1']]])->first();
    }
}
